//
//  MadMainViewController.m
//  MadGTD
//
//  Created by Fuzhou Chen on 4/21/12.
//  Copyright (c) 2012 dummydigit.net. All rights reserved.
//

#import "MadMainViewController.h"

@interface MadMainViewController ()

@end

@implementation MadMainViewController

// UI configuration methods
- (void)adjustSwitchButtonWidth:(UISegmentedControl*)segSwitch
{
    CGFloat totalWidths = 0;
    NSUInteger nSegments = segSwitch.subviews.count;    
    UIView* aSegment = [segSwitch.subviews objectAtIndex:0];
    UIFont* font = nil;
    
    for (UILabel* aLabel in aSegment.subviews) {
        if ([aLabel isKindOfClass:[UILabel class]]) {
            font = aLabel.font;
            break;
        }
    }
    
    for (NSUInteger i=0; i < nSegments; i++) {
        CGFloat textWidth = [[segSwitch titleForSegmentAtIndex:i] sizeWithFont:font].width;
        totalWidths += textWidth;
    }
    
    CGFloat spaceWidth = segSwitch.bounds.size.width - totalWidths;   
    
    for (NSUInteger i=0; i < nSegments; i++) {
        CGFloat textWidth = [[segSwitch titleForSegmentAtIndex:i] sizeWithFont:font].width;
        CGFloat segWidth = roundf(textWidth + (spaceWidth / nSegments) * 3);    
        [segSwitch setWidth:segWidth forSegmentAtIndex:i];
    }
    
}

-(void)configureTodoView
{
    // Main view controller is the only controller to create UIs.
    _todoDetailsController = [[MadTodoDetailsViewController alloc]
                              initWithGTDModel:_model];
    _todoListController = [[MadTodoListController alloc]
                           initWithGTDModel:_model
                           detailsViewController:_todoDetailsController];
    _todoListController.title = _todosLabelText;
    _todoListController.clearsSelectionOnViewWillAppear = NO;
    _navigationController = [[UINavigationController alloc]
                             initWithRootViewController:_todoListController];
    //// Navigation bar has a toolbar for free.
    [_navigationController setToolbarHidden:NO animated:YES];

    self.view.frame = [[UIScreen mainScreen] bounds];
    self.view.autoresizesSubviews = YES;

    _addButton = [[UIBarButtonItem alloc]
                  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                  target:_todoListController
                  action:@selector(insertNewObject:)];

    NSArray *todoTagUILabels = [[NSArray alloc]
                                initWithObjects:_todosLabelText, _tagsLabelText, nil];
    _todosTagsSwitch = [[UISegmentedControl alloc] initWithItems: todoTagUILabels];
    [todoTagUILabels release];

    // The code below is from here:
    // http://stackoverflow.com/questions/9755154/ios-uibarbuttonitem-identifier-option-to-create-settings-cogwheel-button
    // I'm just too lazy to draw a settings button myself. :)
    _settingsButton = [[UIBarButtonItem alloc]
                       initWithTitle:@"\u2699"
                       style:UIBarButtonItemStyleBordered
                       target:_todoListController
                       action:@selector(enterSettings:)];
    UIFont *gearFont = [UIFont fontWithName:@"Helvetica" size:24.0];
    NSDictionary *fontStyle = [[NSDictionary alloc]
                               initWithObjectsAndKeys:gearFont,
                               UITextAttributeFont, nil];
    [_settingsButton setTitleTextAttributes:fontStyle forState:UIControlStateNormal];
    [fontStyle release];

    //// TableViewController has an Edit button for free.
    _todoListController.navigationItem.leftBarButtonItem = _todoListController.editButtonItem;

    [_navigationController.view addSubview:_todoListController.tableView];
    [self.view addSubview:_navigationController.view];

    NSArray *toolBarItems = [[NSArray alloc] initWithObjects:_settingsButton, nil];
    [_todoListController setToolbarItems:toolBarItems];
    [toolBarItems release];

    _todoListController.navigationItem.rightBarButtonItem = _addButton;
    _todosTagsSwitch.segmentedControlStyle = UISegmentedControlStyleBar;
    // Adjust width or the segmented switch will be super ugly!
    [self adjustSwitchButtonWidth:_todosTagsSwitch];

    CGRect todoTagSwitchBounds = _navigationController.toolbar.bounds;
    _todosTagsSwitch.center = CGPointMake(CGRectGetMidX(todoTagSwitchBounds),
                                          CGRectGetMidY(todoTagSwitchBounds));

    [_navigationController.toolbar addSubview: _todosTagsSwitch];    
}

// common methods for UIViewController
- (void)dealloc
{
    [super dealloc];
}

- (id)initWithGTDModel:(MadGTDModel*)model
{
    MAD_CHK_PARAM_OR_TERMINATE(model != nil, ("model == nil"));
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _navigationController = nil;
        _todoDetailsController = nil;
        _todoListController = nil;
        _todosLabelText = @"Todos";
        _tagsLabelText = @"Tags";
        _addButton = nil;
        _todosTagsSwitch = nil;
        _settingsButton =nil;
        
        _model = [model retain];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self configureTodoView];
}

#define RELEASE_IF_EXIST(_obj_) {\
    id _the_object_ = _obj_;\
    if (_the_object_) {\
        [_the_object_ release];\
    }\
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    RELEASE_IF_EXIST(_settingsButton);
    RELEASE_IF_EXIST(_todosTagsSwitch);
    RELEASE_IF_EXIST(_addButton);
    RELEASE_IF_EXIST(_todoListController);
    RELEASE_IF_EXIST(_todoDetailsController);
    RELEASE_IF_EXIST(_navigationController);
    RELEASE_IF_EXIST(_model);
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
